package com.qing.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author qinghua
 * @date 2022/6/13 15:46
 */
@Slf4j
@Component
public class FileUtil {

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    public String upload(MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + originalFilename;
        File file = new File(uploadFolder + newFileName);
        try {
            multipartFile.transferTo(file);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("=====================文件写入失败=====================");
        }
        return staticAccessPath + "/" + newFileName;
    }

    public File getNewFile(String fileName) {
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
        return new File(uploadFolder + newFileName);
    }

}
